<?php
/*
 * @Author: KingMin 
 * @Date: 2021-07-13 22:35:39 
 * @Last Modified by:   KingMin 
 * @Last Modified time: 2021-07-13 22:35:39 
 * @The authors website: https://www.kingmin.cn  
 */
/**
 * 导航
 * @copyright (c) KINGMIN All Rights Reserved
 */

class Navi_Model {

    private $db;

    const navitype_custom  = 0;
    const navitype_home    = 1;
    const navitype_t       = 2;
    const navitype_admin   = 3;
    const navitype_sort    = 4;
    const navitype_page    = 5;

    function __construct() {
        $this->db = Database::getInstance();
    }
    function getqxmenu(){
        $navis = array();
        $query = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_role` ");
        while ($row = $this->db->fetch_array($query)) {
            $navis[]=[
                'role_id'=>$row['role_id'],
                'name'=>$row['role_name'],
                'key'=>$row['role_key'],
                'list'=>self::getjs($row['role_id']),
            ];
        }
        return $navis;
    }
    function getroleList($all='') {
        $wsql='';
        if(!$all){
            $wsql=" AND status = '0'";
        }
        $res = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_role` where isdel='0' $wsql  ORDER BY `role_sort` ASC ");
        $roles = array();
        while($row = $this->db->fetch_array($res)) {
            $role=[];
            $role['role_id'] = htmlspecialchars($row['role_id']);
            $role['role_key'] = htmlspecialchars($row['role_key']);
            $role['data_scope'] = htmlspecialchars($row['data_scope']);
            $role['remark'] = htmlspecialchars($row['remark']);
            $role['role_name'] = htmlspecialchars($row['role_name']);
            $role['role_sort'] = htmlspecialchars($row['role_sort']);
            $role['status'] = htmlspecialchars($row['status']);
            $role['create_by'] = htmlspecialchars($row['create_by']);
            $role['create_time'] = htmlspecialchars($row['create_time']);
            $role['list']=self::getallrolelist($row['role_id']);
            $roles[]=$role;
        }
        return $roles;
    }
    // 获取权限详情
    function getroleDetail($id){
        $res = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_role` where role_id='$id' ");
        $role = array();
        while($row = $this->db->fetch_array($res)) {
            $role['role_id'] = htmlspecialchars($row['role_id']);
            $role['role_key'] = htmlspecialchars($row['role_key']);
            $role['data_scope'] = htmlspecialchars($row['data_scope']);
            $role['remark'] = htmlspecialchars($row['remark']);
            $role['role_name'] = htmlspecialchars($row['role_name']);
            $role['role_sort'] = htmlspecialchars($row['role_sort']);
            $role['status'] = htmlspecialchars($row['status']);
            $role['create_by'] = htmlspecialchars($row['create_by']);
            $role['create_time'] = htmlspecialchars($row['create_time']);
        }
        return $role;
    }
    function getallrolelist($id){
        $navis = array();
        $query = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_role_menu` where `role_id`='$id'");
        while ($row = $this->db->fetch_array($query)) {
            $sql = "select * from `".DB_PREFIX."sys_menu` where `menu_id`='".$row['menu_id']."' ";
            $res = $this->db->query($sql);
            $row = $this->db->fetch_array($res);
            $naviData = array();
            if($row) {
                if($row['menu_type']=='M'){
                    $navis['nodes'][]=$row['menu_id'];
                }else{
                    $navis['keys'][]=$row['menu_id'];
                }
            }
        }
        return $navis;
    }
    function getjs($id){
        $navis = array();
        $query = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_role_menu` where `role_id`='$id'");
        while ($row = $this->db->fetch_array($query)) {
            $navis[]=$row['menu_id'];
        }
        $all=self::getNavis();
        $newlist=[];
        foreach ($all as $k => $v){
            if(in_array($v['id'],$navis )){
                $y=self::getOneNavi($v['id']);
                foreach ($v['children'] as $j => $c){
                    if(in_array($c['id'],$navis )){
                        $y['children'][]=self::getOneNavi($c['id']);
                    }
                }
                $newlist[]=$y;
            }
            
        }
        return $newlist;
    }
    function getNavis() {
        $navis = array();
        $query = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_menu` where `menu_type`='C' ORDER BY order_num ASC");
        while ($row = $this->db->fetch_array($query)) {
            $mid=$row['menu_id'];
            $query1 = $this->db->query("SELECT * FROM `".DB_PREFIX."sys_menu` where `parent_id`='$mid' ORDER BY order_num ASC");
            $children=[];
            while ($r = $this->db->fetch_array($query1)) {
                $v=[
                    'id'=>$r['menu_id'],
                    'title'=>$r['menu_title'],
                    ];
                array_push($children,$v);
            }
            $naviData = array(
                    'id' => $row['menu_id'],
                    'title'=>$row['menu_title'],
                    'children'=>$children
                    );
            $navis[] = $naviData;
        }
        return $navis;
    }

    function updateNavi($naviData, $navid) {
        $Item = array();
        foreach ($naviData as $key => $data) {
            $Item[] = "$key='$data'";
        }
        $upStr = implode(',', $Item);
        $this->db->query("update ".DB_PREFIX."navi set $upStr where id=$navid");
        return true;
    }
    function updaterole($roleData, $id) {
        @$list=$roleData['list'];
        if($list){
            unset($roleData['list']);
            @$upm=$this->uprolemenu($list,$id);
            if(!$upm){
                return false;
            }
        }
        $Item = array();
        foreach ($roleData as $key => $data) {
            $Item[] = "$key='$data'";
        }
        $upStr = implode(',', $Item);
        $this->db->query("update km_sys_role set $upStr where role_id=$id");
        if(!$list){
            $CACHE = Cache::getInstance();
            $CACHE->updateCache('navi');
        }
        return true;
    }
    function uprolemenu($list,$id,$isadd=false){
        if(!$id){
            return false;
        }
        if(!is_array($list)){
            return false;
        }
        if(!$isadd){
            $this->db->query("DELETE FROM `".DB_PREFIX."sys_role_menu` where role_id=$id");
        }
        foreach($list as $k => $v){
            $sql="insert into `".DB_PREFIX."sys_role_menu` (role_id,menu_id) values('$id','$v')";
            $this->db->query($sql);
        }
        $CACHE = Cache::getInstance();
        $CACHE->updateCache('navi');
        return true;
    }

    function addrole($roleData) {
        @$list=$roleData['list'];
        unset($roleData['list']);
        foreach ($roleData as $key => $data) {
            $kItem[] = $key;
            $dItem[] = $data;
        }
        @$field ="`". implode("`,`", $kItem) . "`";
        @$values = "'" . implode("','", $dItem) . "'";
        $sql="insert into km_sys_role ($field)VALUES($values);";
        $res=$this->db->query($sql);
        if($res){
            $id = $this->db->insert_id();
            
            @$upm=$this->uprolemenu($list,$id,true);
            
            if(!$upm){
                return false;
            }
            return true;
        }else{
            return false;
        }
    }
    function addNavi($name, $url, $taxis, $pid, $newtab, $type = 0, $typeId = 0) {
        if($taxis > 30000 || $taxis < 0) {
            $taxis = 0;
        }
        $sql="insert into ".DB_PREFIX."navi (naviname,url,taxis,pid,newtab,type,type_id) values('$name','$url', $taxis, $pid, '$newtab', $type, $typeId)";
        $this->db->query($sql);
    }

    function getOneNavi($navid) {
        $sql = "select * from `".DB_PREFIX."sys_menu` where `menu_id`=$navid ";
        $res = $this->db->query($sql);
        $row = $this->db->fetch_array($res);
        $naviData = array();
        if($row) {
            if($row['menu_type']=='M'){
                $naviData = array(
                    'path' => htmlspecialchars(trim($row['path'])),
                    'component' => htmlspecialchars(trim($row['component'])),
                    'redirect' => htmlspecialchars(trim($row['redirect'])),
                    'alwaysShow' => $row['is_alwaysShow']=='1'?true:false,
                    'hidden' => $row['visible']=='1'?true:false,
                    'meta' => [
                        'title' => htmlspecialchars(trim($row['menu_title'])),
                        'icon' => htmlspecialchars(trim($row['icon'])),
                    ]
                );
            }
            if($row['menu_type']=='C'){
                $naviData = array(
                    'path' => htmlspecialchars(trim($row['path'])),
                    'component' => htmlspecialchars(trim($row['component'])),
                    'name' => htmlspecialchars(trim($row['menu_name'])),
                    'hidden' => $row['visible']=='1'?true:false,
                    'meta' => [
                        'noCache' => $row['is_refresh']=='1'?true:false,
                        'title' => htmlspecialchars(trim($row['menu_title'])),
                        'icon' => htmlspecialchars(trim($row['icon'])),
                    ]
                );
            }
        }
        return $naviData;
    }

    function getNaviNameByUrl($url) {
        $CACHE = Cache::getInstance();
        $navi_cache = $CACHE->readCache('navi');
        foreach($navi_cache as $val) {
            if ($val['url'] == $url){
                return $val['naviname'];
            }
        }

        return '';
    }

    function getNaviNameByType($type) {
        $CACHE = Cache::getInstance();
        $navi_cache = $CACHE->readCache('navi');
        foreach($navi_cache as $val) {
            if ($val['type'] == $type) {
                return $val['naviname'];
            }
        }

        return '';
    }

    function deleteNavi($navid) {
        $this->db->query("DELETE FROM ".DB_PREFIX."navi where id=$navid");
        $this->db->query("UPDATE ".DB_PREFIX."navi set pid=0 where pid=$navid");
    }

}
